﻿using movie.tool.library.binding;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace movie.tool.library.ui
{
    /// <summary>
    /// RichTextEditorControl.xaml 的交互逻辑
    /// </summary>
    public partial class RichTextEditorControl : UserControl
    {
        /// <summary>
        /// 工具类状态
        /// </summary>
        public ToolState State { get; set; }
        public RichTextEditorControl()
        {
            InitializeComponent();
            State = new ToolState();
        }

        private void rtbEditor_SelectionChanged(object sender, RoutedEventArgs e)
        {
            object temp = rtbEditor.Selection.GetPropertyValue(TextElement.FontWeightProperty);
            State.BolderButtonChecked = (temp != DependencyProperty.UnsetValue) && FontWeights.Bold.Equals(temp);
        }

        private void BolderButton_Click(object sender, RoutedEventArgs e)
        {
            if(State.BolderButtonChecked != null && (bool)State.BolderButtonChecked)
            {
                this.rtbEditor.Selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                this.rtbEditor.Selection.ApplyPropertyValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            }
            else
            {
                this.rtbEditor.Selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
            }
        }
        /// <summary>
        /// 从文件加载内容
        /// </summary>
        /// <param name="file">文件路径</param>
        public void Load(string file)
        {
            if (File.Exists(file))
            {
                FileStream fs = new FileStream(file, FileMode.Open);
                TextRange range = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);
                range.Load(fs, DataFormats.Rtf);
            }
        }

        public void Save(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Create);
            TextRange range = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);
            range.Save(fs, DataFormats.Rtf);
        }

        public class ToolState : NotifyPropertyChanged
        {
            private bool? bolderButtonChecked;
            /// <summary>
            /// 加粗按钮选中状态
            /// </summary>
            public bool? BolderButtonChecked { 
                get => bolderButtonChecked;
                set
                {
                    bolderButtonChecked = value;
                    SendPropertyChanged(nameof(BolderButtonChecked));
                }
            }
        }
    }
}
